import { Injectable } from '@nestjs/common';
import { Menu } from '@/entities/menus/menu.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessException } from '@/common/exceptions/business.filter';
import { listToTree } from '@/utils/utils';
import { ToolsService } from '@/service/tools/tools.service';
@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private readonly menuRepository: Repository<Menu>,
    private readonly toolsService: ToolsService,
  ) {}

  /**
   * 获取菜单选项列表(目录或者菜单)
   */
  async getOptions() {
    try {
      //value label children
      let menus = await this.menuRepository.find({
        where: [
          {
            visible: 1,
            type: 1, //目录
          },
          {
            visible: 1,
            type: 2, //菜单
          },
        ],
        order: {
          sort: 'ASC',
        },
      });
      if (!menus) {
        throw new BusinessException('error');
      }
      return listToTree(menus, (item: any) => {
        return {
          label: item.name,
          value: item.id,
          parentId: item.parentId,
          id: item.id,
        };
      });
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  /**
   * 新增加菜单
   */
  async addMenu(body: Menu) {
    return this.toolsService._addEntity(this.menuRepository, body);
  }
  /**
   * 修改菜单信息
   */
  async updateMenu(body: Menu) {
    return this.toolsService._updateEntity(this.menuRepository, body);
  }
  /**
   * 删除菜单
   */
  async removeMenu(id: string) {
    return this.toolsService._deleteEntity(this.menuRepository, id);
  }
  /**
   *
   * 获取菜单列表
   */
  async getMenuList() {
    try {
      let res = await this.menuRepository.find();
      if (!res) {
        throw new BusinessException('error');
      }
      return listToTree(res);
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
}
